<template>
	<div
		class="v-option_item"
		@click.stop="selectOptionClick"
		:class="{ select: active, disabled }"
	>
		{{ currentLabel }}
	</div>
</template>
<script>
import Emitter from "../../assets/emitter";
export default {
	name: "VOption",
	componentName: "VOption",
	mixins: [Emitter],
	data() {
		return {
			active: false,
		};
	},
	inject: ["select"],
	props: {
		value: {
			required: true,
		},
		label: [String, Number],
		disabled: {
			type: Boolean,
			default: false,
		},
	},
	watch: {
		value(val, oldVal) {
			const { remote, valueKey } = this.select;
			if (!this.created && !remote) {
				if (
					valueKey &&
					typeof val === "object" &&
					typeof oldVal === "object" &&
					val[valueKey] === oldVal[valueKey]
				) {
					return;
				}
				this.dispatch("VSelect", "setSelected");
			}
		},
	},
	computed: {
		isObject() {
			return (
				Object.prototype.toString.call(this.value).toLowerCase() ===
				"[object object]"
			);
		},
		currentLabel() {
			return this.label || (this.isObject ? "" : this.value);
		},
	},
	methods: {
		selectOptionClick() {
			if (this.disabled) return;
			this.dispatch("VSelect", "handleOptionClick", [this, true]);
		},
		queryChange(query) {
			this.active = this.value === query;
		},
	},
	created() {
		this.select.options.push(this);
		this.select.cachedOptions.push(this);
		this.$on("queryChange", this.queryChange);
	},
};
</script>
<style lang="less" scoped></style>
